import axios from "axios"
import qs from 'qs'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
let http = axios.create({});
const language = {
    "zhCN": {
        "402": "没有授权",
        "500": "系统错误",
        "501": "没有符合条件的记录",
        "502": "网络繁忙，请重试",
        "503": "上传失败"
    },
    "enUS": {
        "402": "No authorization",
        "500": "System Failure",
        "501": "No qualifying record",
        "502": "Net Busy,Please try again",
        "503": "upload failure,Please select a file"
    }
}
// respone拦截器 响应
http.interceptors.response.use(response => {
    // 只拦截json类型的请求,如果返回流(文件下载)需要放行  
    if (toString.call(response.data) !== "[object Blob]") {
        if (response.data.code === "0") {
            NProgress.done()
            console.log('成功', response)
            //接口调用成功
            return response.data || Promise.resolve(response.data)
        } else {
            NProgress.done()
            console.log('失败', response)
            //接口调用失败
            interceptErrorCode(response)
            //接口调用失败
            return Promise.reject(response.data) || false
        }
    } else {
        NProgress.done()
        return Promise.resolve(response.data)
    }

}, error => {
    // if(error.response.status == 500 ){
    //     return Promise.reject({code:'500',msg:'程序错误'})
    // }
    NProgress.done()
    if (error.response.status) {
        return Promise.reject({ code: error.response.status, msg: error.message })
    }
    return false
})
//请求拦截
http.interceptors.request.use(
    (config) => {
        config.headers['Accept'] = 'application/json, text/plain, */*';
        config.headers['accessToken'] = sessionStorage.getItem("accessToken");
        //get 数组问题处理
        if (config.method === 'get') {
            config.paramsSerializer = function (params) {
                return qs.stringify(params, { arrayFormat: 'repeat' })
            }
        }
        return config;
    },
    //请求失败
    (error: any) => {
        NProgress.done()
        return Promise.reject(error);
    }
)
//扩展方法

function parseData(data: any) {
    var obj = {};
    for (var p in data) {
        if (data[p] === null) {
            continue;
        }
        if(data[p] === undefined){
            continue;
        }
        if (data[p] === "") {
            continue;
        }
        obj[p] = data[p];
    }
    return obj;

}
const sendHttp = (httpOptions: any) => {
    return new Promise((resolve, reject) => {
        return http(httpOptions)
            .then(response => {
                resolve(response)
            }, error => {
                reject(error)
            })
    })
}
//添加全局post 方法
const postByJson = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'post',
        data: data,
    })
}

//全局 导出 表格的请求方法
const postByExport = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'post',
        headers: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8;' },
        data,
        responseType: 'blob',
    })
}

//全局 导出 表格的请求方法
const postBodyByExport = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'post',
        headers: { 'content-type': 'application/json;charset=UTF-8' },
        data: JSON.stringify(data),
        responseType: 'blob',
    })
}

const postForm = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'post',
        data: qs.stringify(parseData(data)),
    })
}

const postBody = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'post',
        headers: { 'content-type': 'application/json' },
        data: JSON.stringify(data),
    })
}

const deleteBody = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'delete',
        headers: { 'content-type': 'application/json' },
        data: JSON.stringify(data),
    })
}

const putBody = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'put',
        headers: { 'content-type': 'application/json' },
        data: JSON.stringify(data),
    })
}

const post = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'post',
        headers: { 'content-type': 'application/json' },
        data: JSON.stringify(data),
    })
}

const get = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'get',
        params: parseData(data)
    })
}

const getByExport = (url: string, data = {}) => {
    return sendHttp({
        url: url,
        method: 'get',
        headers: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8;' },
        params: parseData(data),
        responseType: 'blob',
    })
}


function uploadFilesToServer(url: string, fileName: string, files: []) {
    return new Promise((resolve, reject) => {
        let formData = new FormData();
        files.forEach((file: any) => {
            formData.append(fileName, file as any);
        })
        console.log(formData)
        //添加请求头
        const headers = {
            "Content-Type": "multipart/form-data",
        };
        //配置头
        const request = axios.create({
            headers: {
                'accessToken': sessionStorage.getItem("accessToken"),
                "Content-Type": "multipart/form-data",
            },
        });

        //开始上传
        return request
            .post(url, formData)
            .then((response: any) => {
                resolve(response.data);
            })
            .catch((error) => {
                reject(error);
            });
    })
}

const interceptErrorCode = (response: any) => {
    // 文件下载判定
    const lang = localStorage.getItem("language");
    const res = response.data;
    if (!res.code && res.size && res.type) {
        return;
    }
    if (response.request.responseURL.endsWith("/qms/systemadmin/login/logoutADFS")) {
        if(res.code === '500'){
            // routingOperation()
            // return
        }
    }
    if (res.code === '401') {
        // if (response.request.responseURL.endsWith("/qms/systemadmin/sysUser/findUserInfoByToken")) {
        //     return;
        // }
        //跳转到登录页面
        // routingOperation()
        //1.清除token
        //2.跳转页面 
        return;
        // No authorization
    } else {
        let msgObj = language[lang];
        if (!msgObj) {
            ElMessage.error(res.msg)
            return;
        }
        let text = msgObj[res.msg];
        if (!text) {
            ElMessage.error(res.msg)
        } else {
            ElMessage.error(text)
        }
    }
}

const routingOperation = () => {
    sessionStorage.removeItem("accessToken");
    location.href = "/#/login";
}
export default { ...http, postForm, postByJson, postByExport, getByExport, postBodyByExport, deleteBody, putBody, get, post, uploadFilesToServer, interceptErrorCode, nativeHttp: http };

